<template>
  <div>
    <div style="margin-bottom: 10px">
      <el-input v-model="params.name" placeholder="请输入类名" style="width: 200px"></el-input>
      <el-input v-model="params.description" placeholder="请输入描述" style="width: 200px"></el-input>
      <el-button type="warning" style="margin: 10px" @click="findBySearch()">查询</el-button>
      <el-button type="warning" style="margin: 10px" @click="reset()">清空</el-button>
      <el-popconfirm title="确定删除吗？" @confirm="delBatch()">
        <el-button slot="reference" type="danger" style="margin-left: 5px" v-if="user.role === 'ROLE_ADMIN'">批量删除</el-button>
      </el-popconfirm>
      <el-button type="primary" style="margin-left: 5px" @click="add()" v-if="user.role === 'ROLE_ADMIN'">新增</el-button>
      <el-button type="primary" style="margin-left: 5px" @click="exp()" v-if="user.role === 'ROLE_ADMIN'">批量导出</el-button>
      <el-upload action="http://localhost:8080/api/type/upload"
                 :show-file-list="false"
                 :on-success="successUpload"
                 style="display: inline-block; margin-left: 10px"
        >
        <el-button size="small" type="primary" v-if="user.role === 'ROLE_ADMIN'">批量导入</el-button>
      </el-upload>
    </div>

    <div class="about">
      <el-table :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange" ref="table" :row-key="getRowKeys">
        <el-table-column type="selection" width="55" ref="table" :reserve-selection="true" v-if="user.role === 'ROLE_ADMIN'"></el-table-column>
        <el-table-column prop="name" label="分类名称" width="300"></el-table-column>
        <el-table-column prop="description" label="分类描述" width="300px"></el-table-column>
        <el-table-column label="操作" v-if="user.role === 'ROLE_ADMIN'">
          <template slot-scope="scope">
            <el-button type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-popconfirm title="确定删除吗？" @confirm="del(scope.row.id)">
              <el-button slot="reference" type="danger" style="margin-left: 5px">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

<!--  分页插件  -->
    <div style="margin-top: 10px">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

<!--  新增、编辑  -->
    <div>
      <el-dialog title="请填写信息" :visible.sync="dialogFormVisible" width="30%">
        <el-form :model="form">
          <el-form-item label="分类名称" label-width="15%">
            <el-input v-model="form.name" autocomplete="off" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="分类描述" label-width="15%">
            <el-input v-model="form.description" autocomplete="off" style="width: 80%"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit()">确 定</el-button>
        </div>
      </el-dialog>
    </div>


  </div>
</template>


<script>
import request from "@/utils/request";

export default {
  data() {
    return {
      total: 0,
      params:{
        name: '',
        description: '',
        pageSize:5,
        pageNum:1
      },
      input:'',
      tableData: [],
      form: {},  //form表单对象
      dialogFormVisible: false,  //模态框显示/不显示
      multipleSelection: [],  // 存储勾选后的数据

      user: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {},
    }
  },
  // 页面加载时
  created() {
    this.findBySearch();
  },
  // 页面按钮触发事件时使用的方法
  methods: {

    getRowKeys(row){
      return row.id;
    },


    //2. 模糊查询 + 添加分页
    findBySearch(){
      request.get('/type/search',{params : this.params}).then(res => {
        if (res.code === '0'){
          this.tableData = res.data.list;
          this.total = res.data.total;
        }else {

        }
      })
    },

    //3. 清空查询框
    reset(){
      this.params = {
          description:'',
          name: '',
          pageNum: 1,
          pageSize: 5
      }
      this.findBySearch()
    },

    //4. x条/页 切换
    handleSizeChange(pageSize){  //有回调函数，参数是每页显示条数
      this.params.pageSize = pageSize;
      this.findBySearch();
    },
    //5. 页数切换
    handleCurrentChange(pageNum){  //有回调函数，参数是页数
      this.params.pageNum = pageNum;
      this.findBySearch();
    },

    //6.新增用户
    add(){
      this.form = {};  //原本有个bug,每次新增前，先清空form表单就解决了
      this.dialogFormVisible = true;
    },
    submit(){
      request.post('/type',this.form).then(res => {
        if (res.code === '0'){
          //成功
          this.$message({
            message: '操作成功',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.findBySearch();
        }else {
          //失败
          this.$message({
            message: res.msg,
            type: 'error'
          });

        }
      })
    },

    //7.编辑用户
    edit(obj){
      this.form = obj;
      this.dialogFormVisible = true;
    },

    //8.删除
    del(id){
      request.delete('/type/'+id).then(res => {
        if (res.code === '0'){
          this.$message({
            message: '操作成功',
            type: 'success'
          });
          this.findBySearch()
        }else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      })
    },

    //9. 批量删除
    delBatch(){
      // console.log('最新的表单数据：',this.multipleSelection);
      if(this.multipleSelection.length === 0){
        this.$message.warning('请至少选择一项进行删除');
        return;
      }

      request.put('/type/delBatch',this.multipleSelection).then(res => {
        if (res.code === '0'){
          this.$message.success('批量删除成功')
          this.findBySearch();
        }else {
          this.$message.error(res.msg);
        }
      })

    },

    handleSelectionChange(val){ //只要勾选的框内容发生变化，回调函数就会更新最新内容，放到参数中
      this.multipleSelection = val;
    },

    // 10. 批量导出
    exp(){
      const user = localStorage.getItem('user');
      location.href = 'http://localhost:8080/api/type/export?token=' + JSON.parse(user).token;
    },

    // 11.批量导入：钩子函数监控上传的文件
    successUpload(res){
      if(res.code === '0'){
        this.$message.success('批量导入成功')
        this.findBySearch();
      }else {
        this.$message.error(res.msg);
      }
    }
  }
}
</script>
